package com.yuan.department.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.yuan.department.constants.BaseConstants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: Train
 * @description:
 * @author: yuan_boss
 * @create: 2022-11-23 18:42
 **/
public class BaseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取用户的action
        String action = getActionName(req.getRequestURI());
        //2.判断action是否为空
        if (StringUtils.isEmpty(action)) {
            System.out.println("action不能为空");
            return;
        }

        //3.根据action找到对应的方法
        Method method = null;
        try {
            method = findActionMethod(action);
        } catch (NoSuchMethodException e) {
            System.out.println("在Servlet中没有找到【" + action + "】方法");
        }


        try {
            //4.调用action方法
            String result = executeAction(method,req,resp);
            //5.响应客户端
            if (!StringUtils.isEmpty(result)){
                respClient(result,req,resp);
            }
        } catch (InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }


    }

    //根据方法的返回值响应客户端
    private void respClient(String result, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String[] split = result.split(":");
//        String type = split[0];
//        String page = split[1];
        int index = result.indexOf(":");
        String type = result.substring(0, index); // 获取到跳转的方式
        String page = result.substring(index + 1); // 获取到跳转的页面
        if (BaseConstants.BASE_FORWARD.equals(type)){
            req.getRequestDispatcher("/" + page).forward(req,resp);
        }else if (BaseConstants.BASE_REDIRECT.equals(type)){
            System.out.println(page);
            resp.sendRedirect(req.getContextPath() + "/" + page);
        }else if (BaseConstants.BASE_SCRIPT.equals(type)){
            resp.getWriter().println("<script>alert('"+ page +"');</script>");
        }else if (BaseConstants.BASE_JSON.equals(type)){
            resp.getWriter().println(page);
        }

    }

    //执行方法
    private String executeAction(Method method, HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException {
        return (String)method.invoke(this,req,resp);
    }

    //根据action找到对应的方法
    private Method findActionMethod(String action) throws NoSuchMethodException {
        Method method = this.getClass().getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
        return method;
    }

    //从请求地址中找到调用的action
    private String getActionName(String requestURI) {
        return requestURI.substring(requestURI.lastIndexOf("/") + 1);
    }

    //输出处理
    public String outRedirect(boolean flag,String path){
        if (!flag){
            return BaseConstants.BASE_SCRIPT + ":操作失败";
        }
        return BaseConstants.BASE_REDIRECT + ":" + path;
    }

    public String outResult(boolean flag){
        Map<String,Object> map = new HashMap<>();
        map.put("code",200);
        if (!flag){//操作失败
            map.put("code",100);
            map.put("msg","操作失败");
        }
        String json = JSON.toJSONString(map);
        return BaseConstants.BASE_JSON + ":" + json;
    }
}
